﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using FrontRoomCheck.Model;
using FrontRoomCheck.Properties;
using FrontRoomCheck.SpecialUse;
using FrontRoomCheck.Utiltiy;
using YArchitech.LIB;
using YJKRevitCode.FormUtility.ModelessFormControlSuite.ModelLayer;
using ModelCheckUtility;
using ModelCheckUtility.ControlLayer;
using ModelCheckUtility.ModelLayer;

namespace FrontRoomCheck.ShowDataForm
{
	public partial class FrontRoomCheckForm : System.Windows.Forms.Form, YJKRevitCode.FormUtility.ModelessFormControlSuite.ModelLayer.IModelessFormNoneSwitch
	{
		public IWin32Window RevitHandle
		{
			get
			{
				return this.m_revitHandle;
			}
			private set
			{
				this.m_revitHandle = value;
			}
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public FrontRoomCheckForm(IWin32Window inputHandle, List<ICloseCurveAnalays> input, ExternalCommandData m_commandData)
		{
			this.uidoc = m_commandData.Application.ActiveUIDocument;
			this.document = this.uidoc.Document;
			this.m_revitHandle = inputHandle;
			this.AllRoomPackers = input;
			this.InitializeComponent();
			this.PublicBtn.Checked = true;
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.document).OfClass(typeof(ViewPlan)).WhereElementIsNotElementType();
			foreach (Element element in filteredElementCollector)
			{
				ViewPlan item = element as ViewPlan;
				this.viewList.Add(item);
			}
		}

		private void FrontRoomCheckForm_MouseLeave(object sender, EventArgs e)
		{
			if (!base.ClientRectangle.Contains(base.PointToClient(Cursor.Position)))
			{
				int wMsg = 7;
				FrontRoomCheckForm.SendMessage(SelectFloorForm._hWndSelectFloorForm.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
				return;
			}
			base.Focus();
		}

		private void FrontRoomCheckForm_Load(object sender, EventArgs e)
		{
			//base.Icon = Resource.YArchitechIcon;
			if (!string.IsNullOrEmpty(this.strFormCaption))
			{
				this.Text = this.strFormCaption;
			}
			this.dataGridView1.AutoGenerateColumns = false;
			this.dataGridView1.EnableHeadersVisualStyles = true;
			this.SetRowStyle();
			this.BindData();
		}

		private void BindData()
		{
			int num = 0;
			string guid = FrontRoomCheck.Properties.Resources.GUID;
			InsertData insertData = new InsertData();
			new InsertArea();
			FrontRoomCheck_CmdFrontRoomSurfaceCheck frontRoomCheck_CmdFrontRoomSurfaceCheck = new FrontRoomCheck_CmdFrontRoomSurfaceCheck();
			this.m_RoomTable = new DataTable();
			this.m_RoomTable.Columns.Add("FloorName", typeof(string));
			this.m_RoomTable.Columns.Add("RoomName", typeof(string));
			this.m_RoomTable.Columns.Add("StandardValue", typeof(string));
			this.m_RoomTable.Columns.Add("DesignValue", typeof(string));
			Dictionary<int, List<ICloseCurveAnalays>> dictionary = new Dictionary<int, List<ICloseCurveAnalays>>();
			Dictionary<int, Level> m_Level_index = new Dictionary<int, Level>();
			List<ICloseCurveAnalays> list = new List<ICloseCurveAnalays>();
			list.AddRange(this.AllRoomPackers);
			for (int i = 0; i < list.Count; i++)
			{
				Element thisElement = list[i].GetThisElement();
				insertData = InsertDataToRoom.ReadFromElement<InsertData>(thisElement, guid);
				list[i].RoomType = insertData.FrontRoomType;
				list[i].BuildingType = this.m_strBuildingType;
				if (frontRoomCheck_CmdFrontRoomSurfaceCheck.doCheckFrontChamberStandard(list[i]))
				{
					list.Remove(list[i]);
					i--;
				}
			}
			foreach (ICloseCurveAnalays closeCurveAnalays in list)
			{
				Element thisElement2 = closeCurveAnalays.GetThisElement();
				if (thisElement2 is Room)
				{
					Room room = thisElement2 as Room;
					if (!dictionary.Keys.Contains(room.Level.Id.IntegerValue))
					{
						dictionary.Add(room.Level.Id.IntegerValue, new List<ICloseCurveAnalays>());
						m_Level_index.Add(room.Level.Id.IntegerValue, room.Level);
					}
					dictionary[room.Level.Id.IntegerValue].Add(closeCurveAnalays);
				}
				if (thisElement2 is FilledRegion)
				{
					FilledRegion tmpObj = thisElement2 as FilledRegion;
					Level filledRegionLevel = FrontRoomCheck.Utiltiy.Utility.GetFilledRegionLevel(tmpObj, StaticRescource.m_AllLevels, this.uidoc.ActiveView);
					if (!dictionary.Keys.Contains(filledRegionLevel.Id.IntegerValue))
					{
						dictionary.Add(filledRegionLevel.Id.IntegerValue, new List<ICloseCurveAnalays>());
						m_Level_index.Add(filledRegionLevel.Id.IntegerValue, filledRegionLevel);
					}
					dictionary[filledRegionLevel.Id.IntegerValue].Add(closeCurveAnalays);
				}
			}
			dictionary = (from k in dictionary
			orderby m_Level_index[k.Key].Elevation
			select k).ToDictionary((KeyValuePair<int, List<ICloseCurveAnalays>> k) => k.Key, (KeyValuePair<int, List<ICloseCurveAnalays>> k) => k.Value);
			this.m_RowRoomId.Clear();
			foreach (KeyValuePair<int, List<ICloseCurveAnalays>> keyValuePair in dictionary)
			{
				foreach (ICloseCurveAnalays closeCurveAnalays2 in keyValuePair.Value)
				{
					if (closeCurveAnalays2.GetThisElement() is Room)
					{
						Room room2 = closeCurveAnalays2.GetThisElement() as Room;
						num++;
						int integerValue = room2.Id.IntegerValue;
						insertData = InsertDataToRoom.ReadFromElement<InsertData>(closeCurveAnalays2.GetThisElement(), guid);
						closeCurveAnalays2.RoomType = insertData.FrontRoomType;
						double standardValue = this.GetStandardValue(closeCurveAnalays2.RoomType);
						string name = room2.Level.Name;
						string text = room2.Name;
						text = FrontRoomCheck.Utiltiy.Utility.SubstringRoomName(text);
						string text2;
						if (text == insertData.FrontRoomType)
						{
							text2 = text;
						}
						else
						{
							text2 = text + "(" + insertData.FrontRoomType + ")";
						}
						if (insertData.FrontRoomType == StaticRescource.FrontRoomTypes[0])
						{
							string text3 = standardValue.ToString("f1") + " m^2,最短边>=2.4m";
							string text4 = FrontRoomCheck.Utiltiy.Utility.ChangeAreaByUnit(room2.Area).ToString("f1") + " m^2," + closeCurveAnalays2.AppendValue.ToString("f1") + " m";
							this.m_RoomTable.Rows.Add(new string[]
							{
								name,
								text2,
								text3,
								text4
							});
						}
						else
						{
							string text5 = standardValue.ToString("f1") + " m^2";
							string text6 = FrontRoomCheck.Utiltiy.Utility.ChangeAreaByUnit(room2.Area).ToString("f1") + " m^2";
							this.m_RoomTable.Rows.Add(new string[]
							{
								name,
								text2,
								text5,
								text6
							});
						}
						if (!this.m_RowRoomId.Keys.Contains(num))
						{
							this.m_RowRoomId.Add(num, new List<int>());
						}
						this.m_RowRoomId[num].Add(integerValue);
					}
					if (closeCurveAnalays2.GetThisElement() is FilledRegion)
					{
						FilledRegion filledRegion = closeCurveAnalays2.GetThisElement() as FilledRegion;
						num++;
						int integerValue2 = filledRegion.Id.IntegerValue;
						Level filledRegionLevel2 = FrontRoomCheck.Utiltiy.Utility.GetFilledRegionLevel(filledRegion, StaticRescource.m_AllLevels, this.uidoc.ActiveView);
						insertData = InsertDataToRoom.ReadFromElement<InsertData>(closeCurveAnalays2.GetThisElement(), guid);
						closeCurveAnalays2.RoomType = insertData.FrontRoomType;
						double standardValue2 = this.GetStandardValue(closeCurveAnalays2.RoomType);
						string name2 = filledRegionLevel2.Name;
						string frontRoomType = insertData.FrontRoomType;
						if (insertData.FrontRoomType == StaticRescource.FrontRoomTypes[0])
						{
							string text7 = standardValue2.ToString("f1") + " m^2,最短边>=2.4m";
							string text8 = FrontRoomCheck.Utiltiy.Utility.ChangeAreaByUnit(closeCurveAnalays2.GetArea()).ToString("f1") + " m^2,最短边 " + closeCurveAnalays2.AppendValue.ToString("f1") + " m";
							this.m_RoomTable.Rows.Add(new string[]
							{
								name2,
								frontRoomType,
								text7,
								text8
							});
						}
						else
						{
							string text9 = standardValue2.ToString("f1") + " m^2";
							string text10 = FrontRoomCheck.Utiltiy.Utility.ChangeAreaByUnit(closeCurveAnalays2.GetArea()).ToString("f1") + " m^2";
							this.m_RoomTable.Rows.Add(new string[]
							{
								name2,
								frontRoomType,
								text9,
								text10
							});
						}
						if (!this.m_RowRoomId.Keys.Contains(num))
						{
							this.m_RowRoomId.Add(num, new List<int>());
						}
						this.m_RowRoomId[num].Add(integerValue2);
					}
				}
			}
			this.bdsGrade.DataSource = this.m_RoomTable;
			for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
			{
                this.dataGridView1.Rows[j].Cells[3].Style.ForeColor = System.Drawing.Color.Red;
			}
		}

		private void SetRowStyle()
		{
			this.m_RowStyleAlternate = new DataGridViewCellStyle();
            this.m_RowStyleAlternate.BackColor = System.Drawing.Color.Azure;
            this.m_RowStyleAlternate.SelectionBackColor = System.Drawing.Color.LightGray;
		}

		private void dgvDataTable_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			if (e.ColumnIndex == this.dataGridView1.Columns["FloorNameColumn"].Index)
			{
				DataGridViewRow dataGridViewRow = this.dataGridView1.Rows[e.RowIndex];
				dataGridViewRow.HeaderCell.Value = Convert.ToString(e.RowIndex + 1);
				if (e.RowIndex == 0)
				{
					dataGridViewRow.DefaultCellStyle = this.m_RowStyleAlternate;
					return;
				}
				if (dataGridViewRow.Cells[e.ColumnIndex].Value != DBNull.Value && dataGridViewRow.Cells[e.ColumnIndex].Value != null && dataGridViewRow.Cells[e.ColumnIndex].Value.ToString() == this.dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString())
				{
					dataGridViewRow.DefaultCellStyle = this.dataGridView1.Rows[e.RowIndex - 1].DefaultCellStyle;
					dataGridViewRow.Cells[e.ColumnIndex].Style.ForeColor = dataGridViewRow.DefaultCellStyle.BackColor;
					return;
				}
				if (this.dataGridView1.Rows[e.RowIndex - 1].DefaultCellStyle == this.m_RowStyleAlternate)
				{
					dataGridViewRow.DefaultCellStyle = this.m_RowStyleAlternate;
				}
			}
		}

		private double GetStandardValue(string tmpFrontRoomType)
		{
			double result = 0.0;
			if (this.PublicBtnTag)
			{
				if (tmpFrontRoomType == "前室")
				{
					result = 6.0;
				}
				else if (tmpFrontRoomType == "合用前室")
				{
					result = 10.0;
				}
				else if (tmpFrontRoomType == "特殊合用前室")
				{
					result = 12.0;
				}
			}
			else if (this.HouseBtnTag)
			{
				if (tmpFrontRoomType == "前室")
				{
					result = 4.5;
				}
				else if (tmpFrontRoomType == "合用前室")
				{
					result = 6.0;
				}
				else if (tmpFrontRoomType == "特殊合用前室")
				{
					result = 12.0;
				}
			}
			return result;
		}

		private void TrustBtn_Click(object sender, EventArgs e)
		{
			this.m_strOrderType = "TrustAction";
			this.m_bIfContinue = true;
			this.m_bIfBreak = false;
			this.m_bIfManuEsc = false;
			this.SendEscMessageToRevitAndClearSelect();
			this.m_useBeforeCotinueMethod = new FrontRoomCheckForm.BeforeContinueMethod(this.InsertAreaDataToRoom);
			this.bdsGrade.DataSource = this.m_RoomTable;
			this.dataGridView1.Refresh();
		}

		private void InsertAreaDataToRoom()
		{
			List<int> list = new List<int>();
			List<int> list2 = new List<int>();
			new List<int>();
			list2.Add(0);
			int num = 0;
			for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
			{
				if ((bool)this.dataGridView1.Rows[i].Cells[4].EditedFormattedValue)
				{
					list.Add(i);
				}
			}
			int num2 = 0;
			while (num2 < this.dataGridView1.Rows.Count && num2 != this.dataGridView1.Rows.Count - 2)
			{
				if (this.dataGridView1.Rows[num].Cells[0].EditedFormattedValue.Equals(this.dataGridView1.Rows[num2].Cells[0].EditedFormattedValue))
				{
					num++;
				}
				else
				{
					num++;
					list2.Add(num);
				}
				num2++;
			}
			for (int j = 0; j < list.Count; j++)
			{
				if (list2.Contains(list[j]))
				{
					this.dataGridView1.Rows[list[j]].Cells[0].Style.ForeColor = this.dataGridView1.Rows[list[j]].Cells[0].Style.BackColor;
				}
				else
				{
					this.dataGridView1.Rows[list[j]].Cells[0].Style.ForeColor = this.dataGridView1.Rows[list[j]].Cells[0].Style.BackColor;
				}
			}
			int num3 = 0;
			for (int k = 0; k < list.Count; k++)
			{
				this.m_RoomTable.Rows.Remove(this.m_RoomTable.Rows[list[k]]);
				if (list.Count > k + 1)
				{
					num3++;
					list[k + 1] = list[k + 1] - num3;
				}
			}
			Dictionary<int, List<int>>.Enumerator enumerator = this.m_RowRoomId.GetEnumerator();
			this.dicTrustRoom.Clear();
			this.TrustElems.Clear();
			while (enumerator.MoveNext())
			{
				KeyValuePair<int, List<int>> keyValuePair = enumerator.Current;
				int item = keyValuePair.Key - 1;
				foreach (int key in keyValuePair.Value)
				{
					if (list.Contains(item))
					{
						this.dicTrustRoom.Add(key, this.m_strBuildingType);
					}
				}
			}
		}

		private void FilterTrustElem(List<ICloseCurveAnalays> input)
		{
			InsertArea insertArea = new InsertArea();
			string areaGuid = FrontRoomCheck.Properties.Resources.AreaGuid;
			for (int i = 0; i < input.Count; i++)
			{
				insertArea = InsertDataToRoom.ReadAreaFromElement<InsertArea>(input[i].GetThisElement(), areaGuid);
				if (insertArea.m_TrustNum == 1 && this.m_strBuildingType == insertArea.m_BuildingType)
				{
					input.Remove(input[i]);
					i--;
				}
				else if (insertArea.m_TrustNum > 1)
				{
					input.Remove(input[i]);
					i--;
				}
			}
		}

		private void CloseBtn_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			this.m_strOrderType = "doubleClick";
			this.m_bIfContinue = true;
			this.m_bIfBreak = false;
			this.m_bIfManuEsc = false;
			this.SendEscMessageToRevitAndClearSelect();
			this.m_useBeforeCotinueMethod = new FrontRoomCheckForm.BeforeContinueMethod(this.LocationMethod);
		}

		private void LocationMethod()
		{
			List<int> list = new List<int>();
			DataGridViewCell dataGridViewCell = null;
			DataGridViewSelectedCellCollection selectedCells = this.dataGridView1.SelectedCells;
			IEnumerator enumerator = selectedCells.GetEnumerator();
			{
				if (enumerator.MoveNext())
				{
					DataGridViewCell dataGridViewCell2 = (DataGridViewCell)enumerator.Current;
					dataGridViewCell = dataGridViewCell2;
				}
			}
			List<int> list2 = new List<int>();
			if (dataGridViewCell.RowIndex == -1)
			{
				return;
			}
			if (dataGridViewCell.ColumnIndex != -1 || dataGridViewCell.RowIndex != -1)
			{
				this.m_RowRoomId.TryGetValue(dataGridViewCell.RowIndex + 1, out list2);
			}
			Selection selection = this.uidoc.Selection;
			List<Element> list3 = new List<Element>();
			ElementSet elementSet = new ElementSet();
			ElementId elementId = null;
			ElementId elementId2 = new ElementId(list2[0]);
			Element element = this.document.GetElement(elementId2);
			if (element is Room)
			{
				elementId = element.LevelId;
				list3.Add(element);
				elementSet.Insert(element);
			}
			else if (element is FilledRegion)
			{
				list.Add(element.Id.IntegerValue);
			}
			if (list.Count > 0)
			{
				this.ChangeFilledRegionVisible(list);
			}
			foreach (ViewPlan viewPlan in this.viewList)
			{
				int integerValue = elementId.IntegerValue;
				if (viewPlan.GenLevel != null && viewPlan.GenLevel.Id.IntegerValue == integerValue)
				{
					this.uidoc.ActiveView = viewPlan;
					break;
				}
			}
			this.uidoc.ShowElements(elementSet);
			RevitVersionFuncs.SetSelection(selection, list3);
			this.uidoc.RefreshActiveView();
		}

		private void FrontRoomCheckForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			List<int> notDeleteRoom = FrontRoomCheck.Utiltiy.Utility.GetNotDeleteRoom(this.document);
			ElementPackerManger.TryDeletedAddedRoom(this.document, notDeleteRoom);
		}

		private void PublicBtn_Click(object sender, EventArgs e)
		{
			this.PublicBtnTag = true;
			this.HouseBtnTag = false;
			this.m_strBuildingType = StaticRescource.BuildingTypes[1];
			this.lstPublicRoomPackers.Clear();
			this.lstPublicRoomPackers.AddRange(this.AllRoomPackers);
			this.FilterTrustElem(this.lstPublicRoomPackers);
			this.BindData();
		}

		private void HouseBtn_Click(object sender, EventArgs e)
		{
			this.PublicBtnTag = false;
			this.HouseBtnTag = true;
			this.m_strBuildingType = StaticRescource.BuildingTypes[0];
			this.lstHouseRoomPackers.Clear();
			this.lstHouseRoomPackers.AddRange(this.AllRoomPackers);
			this.FilterTrustElem(this.lstHouseRoomPackers);
			this.BindData();
		}

		protected override bool ProcessKeyEventArgs(ref Message m)
		{
			int num = 256;
			int num2 = 27;
			if (m.Msg == num && m.WParam.ToInt32() == num2)
			{
				base.Close();
			}
			return base.ProcessKeyEventArgs(ref m);
		}

		public bool IfBreak
		{
			get
			{
				return this.m_bIfBreak;
			}
		}

		public bool IfContinue
		{
			get
			{
				return this.m_bIfContinue;
			}
		}

		public bool IfManualEsc
		{
			get
			{
				return this.m_bIfManuEsc;
			}
		}

		public void CloseForm()
		{
			if (!base.IsDisposed)
			{
				base.Close();
			}
		}

		public void ResetContinueBreak()
		{
			this.m_bIfContinue = false;
			this.m_bIfBreak = true;
			this.m_bIfManuEsc = true;
		}

		public void SendEscMessageToRevitAndClearSelect()
		{
			this.m_useBeforeCotinueMethod = null;
			RevitVersionFuncs.ClearSelection(this.uidoc.Selection);
			ModelCheckUtility.Utility.SendEscToHandle(this.RevitHandle);
		}

		public void ShowForm(IWin32Window parentForm = null)
		{
			if (this.RevitHandle != null)
			{
				base.Show(this.RevitHandle);
				return;
			}
			base.Show();
		}

		public void DoBeforeContinue()
		{
			if (this.m_useBeforeCotinueMethod != null)
			{
				this.m_useBeforeCotinueMethod();
			}
		}

		public void ChangeFilledRegionVisible(List<int> lstFilledRegionIds)
		{
			Document document = this.uidoc.Document;
			Transaction transaction = new Transaction(document, "changeFilledRegionVisible");
			List<ElementId> list = new List<ElementId>();
			foreach (int num in lstFilledRegionIds)
			{
				list.Add(new ElementId(num));
			}
			if (list.Count == 0 && (list == null || this.m_lstFrontElmentId.Count == 0))
			{
				return;
			}
			try
			{
				transaction.Start();
				if (this.m_frontViewPlan != null && this.m_lstFrontElmentId != null && this.m_lstFrontElmentId.Count > 0)
				{
					this.m_frontViewPlan.HideElements(this.m_lstFrontElmentId);
				}
				if (list.Count > 0)
				{
					document.ActiveView.UnhideElements(list);
				}
				transaction.Commit();
			}
			catch (Exception)
			{
				if (transaction.HasStarted())
				{
					transaction.RollBack();
				}
			}
			finally
			{
				this.m_frontViewPlan = (document.ActiveView as ViewPlan);
				this.m_lstFrontElmentId = list;
			}
		}

		private IWin32Window m_revitHandle;

		private FrontRoomCheckForm.BeforeContinueMethod m_useBeforeCotinueMethod;

		private List<ElementId> m_lstFrontElmentId = new List<ElementId>();

		private List<AdapteRoomResulePacker> m_inputValue = new List<AdapteRoomResulePacker>();

		public Dictionary<int, string> dicTrustRoom = new Dictionary<int, string>();

		private ViewPlan m_frontViewPlan;

		public string strFormCaption;

		public string m_strOrderType = " ";

		private List<ICloseCurveAnalays> AllRoomPackers = new List<ICloseCurveAnalays>();

		private bool PublicBtnTag = true;

		private bool HouseBtnTag;

		private string m_strBuildingType = StaticRescource.BuildingTypes[1];

		private List<ICloseCurveAnalays> lstPublicRoomPackers = new List<ICloseCurveAnalays>();

		private List<ICloseCurveAnalays> lstHouseRoomPackers = new List<ICloseCurveAnalays>();

		private DataGridViewCellStyle m_RowStyleAlternate;

		private DataTable m_RoomTable;

		private List<int> TrustElems = new List<int>();

		private Document document;

		public UIDocument uidoc;

		private List<ViewPlan> viewList = new List<ViewPlan>();

		private Dictionary<int, List<int>> m_RowRoomId = new Dictionary<int, List<int>>();

		private delegate void BeforeContinueMethod();
	}
}
